<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-08-22 17:52:38
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\basicData\institution.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      :inline="true"
    >
      <el-form-item label="收款单位名称">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="getList()"
        />
      </el-form-item>
      <el-form-item label="收款账户">
        <el-input
          v-model="queryParams.paymentAccount"
          placeholder="请输入"
          clearable
          @keyup.enter.native="getList()"
        />
      </el-form-item>
      <el-form-item label-width="20px">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getList()"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="reset()"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <div class="table-wrapper">
      <div class="tableoperation">
        <el-button
          type="primary"
          v-hasPermi="['basic:agreementPaymentInfo:add']"
          icon="el-icon-plus"
          size="mini"
          @click.native.prevent="openDialog(null, 'add')"
          >添加</el-button
        >
      </div>

      <vxe-table
        resizable
        border="inner"
        ref="paymentTable"
        :tree-config="{}"
        :data="payMentList"
        show-overflow
        :row-config="{
          useKey: true,
          keyField: 'paymentInfoId',
        }"
        height="600px"
        v-loading="loading"
      >
        <vxe-column title="序号" align="center" width="50" field="center">
          <template #default="scope">
            {{ scope.$rowIndex + 1 }}
          </template>
        </vxe-column>
        <vxe-column title="收款单位名称" align="center" field="unitName" />
        <vxe-column title="收款账户" align="center" field="paymentAccount" />
        <vxe-column align="center" title="操作" width="200">
          <template #default="{ row }">
            <el-button
              @click.native.prevent="openDialog(row, 'edit')"
              type="text"
              v-if="
                checkPermi(['basic:agreementPaymentInfo:edit']) && row.beOperate
              "
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="handleDelete(row)"
              type="text"
              v-if="
                checkPermi(['basic:agreementPaymentInfo:delete']) &&
                row.beOperate
              "
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <!-- <el-table v-loading="loading" :data="payMentList">
			<el-table-column label="序号" type="index" width="50" align="center" />
			<el-table-column label="收款单位名称" align="center" prop="unitName"/>
			<el-table-column label="收款账户" align="center" prop="paymentAccount"/>
			<el-table-column
        align="center"
        label="操作"
				width="200">
        <template slot-scope="{row}">
					<el-button
						@click.native.prevent="openDialog(row, 'edit')"
						type="text">
						编辑
					</el-button>
          <el-button
            @click.native.prevent="handleDelete(row)"
            type="text"
						style="color: #f32d2d">
            删除
          </el-button>
        </template>
      </el-table-column>
		</el-table> -->

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加修改弹框 -->
    <AddEditPaymentDialog
      :show.sync="showPaymentDialog"
      :operType="operType"
      :row="currRow"
      @refresh="getList"
    ></AddEditPaymentDialog>
  </div>
</template>

<script>
import {
  getPaymentListAll,
  removePaymentInfo,
  dragePaymentOrder,
} from "@/api/person/payment";
import AddEditPaymentDialog from "./components/addEditPaymentDialog";
import Sortable from "sortablejs";

export default {
  name: "payment",
  components: { AddEditPaymentDialog },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      // 机构列表
      payMentList: [],
      // 表单参数
      form: {},
      loading: false,
      showPaymentDialog: false,
      currRow: {},
      operType: "add",
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.rowDrop();
  },
  methods: {
    // 获取场所列表
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      delete params.pageNum;
      delete params.pageSize;
      getPaymentListAll(params)
        .then((response) => {
          this.payMentList = response.data || [];
          this.total = response.total || 0;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 点击
    openDialog(row, type) {
      this.operType = type;
      this.currRow = row;
      this.showPaymentDialog = true;
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除[${row.unitName}]？`)
        .then(() => {
          this.loading = true;
          return removePaymentInfo(row.paymentInfoId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 表单查询
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },

    rowDrop() {
      // 获取容器元素
      let el = document.querySelector(
        ".body--wrapper > .vxe-table--body tbody"
      );
      if (!el) return;
      this.sortableObj = new Sortable(el, {
        ghostClass: "ghost",
        draggable: ".vxe-body--row",
        animation: 350,
        scroll: true,
        onMove: (evt) => {
          const { dragged, related } = evt;
          const dragElClassList = [];
          dragged.classList.forEach((element) => {
            if (element.includes("row--level")) {
              dragElClassList.push(element);
            }
          });

          const relatelClassList = [];
          related.classList.forEach((element) => {
            if (element.includes("row--level")) {
              relatelClassList.push(element);
            }
          });
          // 不同层级的不能互相拖动
          // isEqual采用lodash的方法，判断两个值是否相等
          if (!this.$lodash.isEqual(dragElClassList, relatelClassList))
            return false;
          return true;
        },
        onEnd: (evt) => {
          const { newIndex, oldIndex } = evt;
          if (newIndex === oldIndex) return;
          const expandRow = this.$refs.paymentTable.getTreeExpandRecords();
          // 展开的数据id
          const expandId = expandRow?.map((item) => item.paymentInfoId);
          // 建立映射
          let count = -1;
          const result = {};
          const getMap = (data, parentIndex = "") => {
            data.forEach((item, index) => {
              // 如果有子类，将子类也push进去
              item.selfIndex =
                parentIndex === "" ? `${index}` : `${parentIndex}-${index}`;
              result[++count] = item.selfIndex;
              if (
                expandId.includes(item.paymentInfoId) &&
                item.children &&
                item.children.length > 0
              ) {
                getMap(item.children, item.selfIndex);
              }
            });
          };
          const cloneData = this.payMentList?.map((o) => o);
          // 判断有几个'-'
          const countDashes = (str) => {
            let matches = str.match(/-/g);
            return matches ? matches.length : 0;
          };
          getMap(cloneData);
          // 根据映射获取对应数据真正的索引
          const oldRealIndex = result[oldIndex];
          const newRealIndex = result[newIndex];
          if (oldRealIndex.length < 3 && newRealIndex.length < 3) {
            const currRow = this.$lodash.cloneDeep(
              this.payMentList[oldRealIndex]
            ); // 拖动的节点
            this.payMentList?.splice(oldRealIndex, 1);
            this.payMentList?.splice(newRealIndex, 0, currRow);
            this.getOptions(newRealIndex, this.payMentList, currRow);
          } else {
            // 判断子节点是否在同一个父节点当中
            // 获取截取'-'第一个字符的长度
            const firstOldNumLength = oldRealIndex.split("-")[0].length;
            const firstNewNumLength = newRealIndex.split("-")[0].length;
            const oldParentFirstChart = oldRealIndex.slice(
              0,
              firstOldNumLength
            );
            const newParentFirstChart = newRealIndex.slice(
              0,
              firstNewNumLength
            );
            if (oldParentFirstChart !== newParentFirstChart) {
              this.$modal.msgWarning("只能在同一目录下修改排序");
              this.$refs.paymentTable.reloadData(this.payMentList);
              this.$nextTick(() => {
                this.$refs.paymentTable.setTreeExpand(expandRow, true);
              });
              return;
            }
            // 判断索引长度
            const lineNum = countDashes(oldRealIndex);
            const childIndexLength = oldRealIndex.split("-")[lineNum].length;
            const parentIndex = oldRealIndex.slice(
              0,
              childIndexLength > 1 ? -3 : -2
            );
            const tempOldIndex = oldRealIndex.slice(
              oldRealIndex.length - (childIndexLength > 1 ? 2 : 1)
            );
            const tempNewIndex = newRealIndex.slice(
              oldRealIndex.length - (childIndexLength > 1 ? 2 : 1)
            );
            const getCurrent = (arr) => {
              arr.forEach((item) => {
                if (item.selfIndex === parentIndex && item.children?.length) {
                  const currRow = item.children[tempOldIndex];
                  item.children?.splice(tempOldIndex, 1);
                  item.children?.splice(tempNewIndex, 0, currRow);
                  this.getOptions(tempNewIndex, item.children, currRow);
                }
                if (item.children?.length) {
                  getCurrent(item.children);
                }
              });
            };
            getCurrent(this.payMentList);
          }
          // 赋值到数据,可以传给后端
          this.$refs.paymentTable.reloadData(this.payMentList);
          this.$nextTick(() => {
            this.$refs.paymentTable.setTreeExpand(expandRow, true);
          });
        },
      });
    },
    // 获取拖拽排序要提交的数据
    getOptions(index, list, row) {
      let site = this.findDragSite(index, list);
      let options = {};
      switch (site) {
        case "first":
          options = {
            parentId: row.parentId,
            orderNum: Math.floor(list[+index + 1].sort / 2),
          };
          break;
        case "last":
          options = {
            parentId: row.parentId,
            orderNum: list[+index - 1].sort + 10000,
          };
          break;
        default:
          options = {
            parentId: row.parentId,
            orderNum: Math.floor(
              (list[+index - 1].sort + list[+index + 1].sort) / 2
            ),
          };
      }
      console.log(options);
      dragePaymentOrder(row.paymentInfoId, options).then((res) => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      });
    },
    // 拖拽位置
    findDragSite(index, list) {
      if (index == "0") {
        return "first";
      } else if (list.length - 1 == index) {
        return "last";
      } else {
        return "inner";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.operation {
  margin: 20px 0 30px 0;
}
// ::v-deep .pagination-container {
// margin-top: 70px;
// }
</style>
